package io.github.kimmking.gateway.router.my;

import io.github.kimmking.gateway.router.HttpEndpointRouter;

import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 随机权重
 */
public class MyWeightHttpEndpointRouter implements HttpEndpointRouter {

    private List<Integer> weightList;

    public MyWeightHttpEndpointRouter(List<Integer> weightList) {
        this.weightList = weightList;
    }

    @Override
    public String route(List<String> urls) {
        int total = 0;//总权重
        TreeMap<Integer, String> map = new TreeMap<>();
        for (int i = 0; i < urls.size(); i++) {
            total += weightList.get(i);
            map.put(total, urls.get(i));
        }

        int random = (int) (Math.random() * total) + 1;
        Integer key = map.ceilingKey(random);
        return map.get(key);
    }


}
